package controllers.manage.merchant;

import bill.WithdrawalsBill;
import controllers.BaseController;
import controllers.auth.SkipAuth;
import enums.ReviewStatus;
import helper.AliyunOssUploader;
import helper.CSVUtils;
import helper.GlobalConfig;
import jodd.util.StringUtil;
import models.constants.DeletedStatus;
import models.merchant.Merchant;
import models.merchant.enums.VerifyState;
import models.msgtemp.admin.WxMpAdminMsgTemp;
import models.msgtemp.merchant.WxMpMerchantMsgTemp;
import models.weixin.WeixinData;
import play.Logger;
import play.Play;
import play.modules.paginate.JPAExtPaginator;
import play.mvc.Controller;
import play.mvc.With;
import product.Product;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.util.*;

/**
 * 商户管理
 * Created by hanbin on 17/4/6.
 */
@With(BaseController.class)
public class MerChantCtrl extends Controller {
    public static final Integer PAGE_SIZE = 20;
    /**
     * 跳转到商户管理页面
     */
    public static void index(Integer pageNumber, String merchantName,String phone,String loginName,VerifyState verifyState){
        pageNumber = pageNumber == null ? 1 : pageNumber;
        Map<String , Object> searchMap = new HashMap<>();
        String orderStr = " createAt desc ";
        if(verifyState != null && !verifyState.equals("")) {
            searchMap.put("verifyState",verifyState);

        }else{
            orderStr ="  field(verifyState,'VERIFY','WAIT','PASS','CLOSE','NOTPASS')";
        }
        if(StringUtil.isNotBlank(merchantName)) {
            searchMap.put("merchantName", "%"+merchantName+"%");
        }
        if(StringUtil.isNotBlank(phone)) {
            searchMap.put("phone", phone);
        }
        if(StringUtil.isNotBlank(loginName)) {
            searchMap.put("loginName", loginName);
        }
        flash.put("menuId", "2");
        JPAExtPaginator<Merchant> resultPage = Merchant.findByCondition(searchMap, orderStr, pageNumber, PAGE_SIZE);
        render(resultPage, pageNumber,verifyState,merchantName,phone,loginName);
    }

    /**
     * 跳转到新增商户页面
     */
    public static void add(){
        List<WeixinData> weixinDatas = WeixinData.findAllWeixinData();
        render(weixinDatas);
    }

    /**
     * 跳转到修改商户页面
     */
    public static void modify(long id, Integer pageNumber){
        List<WeixinData> weixinDatas = WeixinData.findAllWeixinData();
        Merchant merchant = Merchant.findById(id);
        // 二维码
        String qrCodeBase = "";
        String urlBase = "";
        String urlStr = "";
        if(merchant != null){
            urlBase = Play.configuration.getProperty("weixin.merchant.url");
            urlStr = Play.configuration.getProperty("weixin.merchant.qrCode.url")+merchant.linkId;
        }
        qrCodeBase = urlBase + urlStr ;
        render(merchant, pageNumber, weixinDatas,qrCodeBase);
    }


    /**
     * 创建商户
     */
    public static void create(Merchant merchant , File imagePath){
        try {
            if(imagePath != null) {
                BufferedImage sourceImg = ImageIO.read(new FileInputStream(imagePath));
                Integer width = sourceImg.getWidth();
                Integer height = sourceImg.getHeight();
                if(((double)width/(double)height) != ((double)4/(double)3)){
                    merchant.deleted = DeletedStatus.UN_DELETED;
                    merchant.save();
                    flash.put("msg" , "图片比例不是4:3");
                    modify(merchant.id, 1);
                }
                merchant.imagePath = AliyunOssUploader.uploadPublicFile(imagePath , 300);
            }
            merchant.deleted = DeletedStatus.UN_DELETED;
            merchant.save();
            flash.put("msg" , "商户创建成功");
            redirect("/BS0007/admin/merchant/index/1");
        } catch (Exception e) {
            Logger.warn(e, "LOG01750: merchant create failed!");
        }
    }

    /**
     * 修改商户
     */
    public static void update(Long merchantId, Merchant merchant, Integer pageNumber , File imagePath, VerifyState verifyState){
        Logger.info("merchant.merchantId=============== ================ ：%s",merchantId);
        Logger.info("verifyState ================ ：%s",verifyState);
        try {
            merchant.verifyState = verifyState;
            Merchant.update(merchantId , merchant);
            List<Product> productList = Product.findAllProducts(merchantId);
            for(Product product : productList){
                product.reviewStatus = ReviewStatus.FROZEN;
             //   AliyunOpenSearch.uploadProductByRiZhi(product);
            }
            if(merchant.verifyState ==  VerifyState.CLOSE){
                flash.put("msg" , "商户店铺关闭");
            }else{
                flash.put("msg" , "商户审核完成");
            }
            redirect("/BS0007/admin/merchant/index/"+pageNumber);
        } catch (Exception e) {
            Logger.warn(e, "LOG01750: merchant update failed!");
        }
    }

    /**
     * 删除商户
     */
    public static void delete(long id , Integer pageNumber){
        pageNumber = pageNumber == null ? 1 : pageNumber;
        Merchant merchant = Merchant.findById(id);
        //判断merchant是否被使用
        if(Merchant.checkIsUsed(id)){
            flash.put("msg" , "场馆正在被使用,无法删除!");
            redirect("/BS0007/admin/merchant/index/"+pageNumber);
        }
        merchant.deleted=DeletedStatus.DELETED;
        merchant.save();
        flash.put("msg" , "场馆删除成功");
        redirect("/BS0007/admin/merchant/index/"+pageNumber);
    }


    @SkipAuth
    public static void popMerchant(Integer pageNumber, String name){
        pageNumber = pageNumber == null ? 1 : pageNumber;
        Map<String , Object> searchMap = new HashMap<>();
        searchMap.put("verifyState",VerifyState.PASS);
        if(StringUtil.isNotBlank(name)) {
            searchMap.put("name", "%"+name+"%");
        }

        JPAExtPaginator<Merchant> resultPage = Merchant.findByCondition(searchMap, "id desc", pageNumber, GlobalConfig.PAGE_SIZE);
        render(resultPage, pageNumber, name);
    }
    /**
     * 跳转到修改商户页面
     */
    public static void closeMer(long id, Integer pageNumber){
        List<WeixinData> weixinDatas = WeixinData.findAllWeixinData();
        Merchant merchant = Merchant.findById(id);
        // 二维码
        String qrCodeBase = "";
        String urlBase = "";
        String urlStr = "";
        if(merchant != null){
            urlBase = Play.configuration.getProperty("weixin.merchant.url");
            urlStr = Play.configuration.getProperty("weixin.merchant.qrCode.url")+merchant.linkId;
        }
        qrCodeBase = urlBase + urlStr ;
        render(merchant, pageNumber, weixinDatas ,qrCodeBase);
    }


    /**
     * 跳转到修改商户页面
     */
    public static void goGrade(long id, Integer pageNumber){
        List<WeixinData> weixinDatas = WeixinData.findAllWeixinData();
        Merchant merchant = Merchant.findById(id);
        render(merchant, pageNumber, weixinDatas);
    }

    public static  void  updateStarNum(Long merchantId, Merchant merchant, Integer pageNumber ){
        Logger.info("merchant.merchantId=============== ================ ：%s",merchantId);
        Logger.info("merchant.starNum=============== ================ ：%s",merchant.starNum);
        Merchant newMer = Merchant.findByMerchantId(merchantId);
        newMer.starNum = merchant.starNum;
        newMer.save();
        flash.put("msg" , "商户评分完成");
        redirect("/BS0007/admin/merchant/index/"+pageNumber);

    }

    //商户审核
    public static void auditMerchant(Long merchantId , VerifyState verifyState , Integer pageNumber){
        if(merchantId == null){
            flash.put("msg" , "商户信息获取不成功,审核失败!");
            redirect("/BS0007/admin/merchant/index/"+pageNumber);
        }
        if(verifyState == null || (verifyState != VerifyState.PASS && verifyState != VerifyState.NOTPASS )){
            flash.put("msg" , "审核信息错误,审核失败!");
            redirect("/BS0007/admin/merchant/index/"+pageNumber);
        }

        Merchant merchant = Merchant.findByMerchantId(merchantId);
        if(merchant == null){
            flash.put("msg" , "商户信息获取不成功,审核失败!");
            redirect("/BS0007/admin/merchant/index/"+pageNumber);
        }

        merchant.verifyState = verifyState;
        merchant.save();

        if(merchant.verifyState ==  VerifyState.NOTPASS){
            List<Product> productList = Product.findAllProducts(merchantId);
            for (Product product : productList) {
                product.reviewStatus = ReviewStatus.FROZEN;
              //  AliyunOpenSearch.uploadProductByRiZhi(product);
                product.save();
            }
            WxMpAdminMsgTemp.sendMsgforNotPassMerchant(merchant);
            flash.put("msg" , "商户信息审核不通过!");

        }else{
            List<Product> productList = Product.findAllProducts(merchantId);
            for (Product product : productList) {
             //   AliyunOpenSearch.uploadProductByRiZhi(product);
                product.save();
            }
            Logger.info("merchant.verifyState ：%s","pass");
            flash.put("msg" , "商户审核通过!");
        }

        WxMpMerchantMsgTemp.sendMsgforAuditMerchant(merchant);

        pageNumber = pageNumber == null ? 1 : pageNumber;
        redirect("/BS0007/admin/merchant/index/"+pageNumber);

    }

    // 商户冻结
    public static void freezingMerchant(Long merchantId ,  Integer pageNumber){
        if(merchantId == null){
            flash.put("msg" , "商户信息获取不成功,冻结失败!");
            redirect("/BS0007/admin/merchant/index/"+pageNumber);
        }

        Merchant merchant = Merchant.findByMerchantId(merchantId);
        if (merchant == null) {
            flash.put("msg", "商户信息获取不成功,冻结失败!");
            redirect("/BS0007/admin/merchant/index/" + pageNumber);
        }

        merchant.verifyState = VerifyState.NOTPASS;
        merchant.save();
        List<Product> productList = Product.findAllProducts(merchantId);
        for (Product product : productList) {
            product.reviewStatus = ReviewStatus.FROZEN;
          //  AliyunOpenSearch.uploadProductByRiZhi(product);
            product.save();
        }
        flash.put("msg", "商户已冻结成功!");

        WxMpAdminMsgTemp.sendMsgforFreezingMerchant(merchant);

        pageNumber = pageNumber == null ? 1 : pageNumber;
        redirect("/BS0007/admin/merchant/index/"+pageNumber);
    }


    /**
     * 跳转到查看商户页面
     */
    public static void goSee(long id, Integer pageNumber){
        List<WeixinData> weixinDatas = WeixinData.findAllWeixinData();
        Merchant merchant = null;
        merchant = Merchant.findById(id);
        // 二维码
        String qrCodeBase = "";
        String urlBase = "";
        String urlStr = "";
        List<Product> productList = new ArrayList<>();
        String sumBuyNum = "";
        String sumAmount = "";
        Integer proCout = 0;
        if(merchant != null){
             urlBase = Play.configuration.getProperty("weixin.merchant.url");
             urlStr = Play.configuration.getProperty("weixin.merchant.qrCode.url")+merchant.linkId;
            // 产品数量
            productList = Product.getProductListByMerId(merchant.id);
            // 产品销量
            List<Map<String, Object>> buyNumberMap = Merchant.loadOrderBuyNumberByMerchants(merchant.id);
            for(Map<String, Object> map : buyNumberMap){
                sumBuyNum = map.get("buyNumber").toString();
            }
            //销售额
            List<Map<String, Object>> sumAmountMap = Merchant.loadSumAmountByMerchants(merchant.id);
            for(Map<String, Object> map : sumAmountMap){
                sumAmount = map.get("sumAmount").toString();
            }


        }
        proCout = productList.size();
         qrCodeBase = urlBase + urlStr ;

        render(merchant, pageNumber, weixinDatas ,qrCodeBase,proCout,sumBuyNum,sumAmount);
    }

    /**
     * 跳转到商户管理页面
     */
    public static void withdrawList(Integer pageNumber, Long merId,String startTime,String endTime){
        pageNumber = pageNumber == null ? 1 : pageNumber;
        Map<String , Object> searchMap = new HashMap<>();
        String orderStr = "  createAt desc ";
        if(merId != null ) {
            searchMap.put("merId",merId);
        }
        if(StringUtil.isNotBlank(startTime)) {
            searchMap.put("startTime", startTime+" 00:00:00");
        }

        if(StringUtil.isNotBlank(endTime)) {
            searchMap.put("endTime", endTime+" 23:59:59");
        }
        JPAExtPaginator<WithdrawalsBill> resultPage = WithdrawalsBill.findByCondition(searchMap, orderStr, pageNumber,GlobalConfig.PAGE_SIZE);
        render(resultPage, pageNumber,merId,startTime,endTime);
    }

    //导出
    public static void exportExcel(String merchantName,String phone,String loginName,VerifyState verifyState){

       List<Map<String,Object>> listMap = Merchant.loadMerchantsByExcle(merchantName,phone,loginName,verifyState);

        //标题
        LinkedHashMap<String,String> headerMap = new LinkedHashMap<>();
        headerMap.put("name","商户名称");
        headerMap.put("type","商户类型");
        headerMap.put("realName","真实姓名");
        headerMap.put("classes","班级");
        headerMap.put("servicePhone","手机号码");
        headerMap.put("weChat","微信号");
        headerMap.put("pcount","产品数量");

        //数据列表
        List<Map> dataList = new ArrayList<>();
            for(Map<String,Object> map : listMap){
                Map<String,Object> row = new LinkedHashMap<>();
                row.put("name",map.get("name").toString());

                if(map.get("type") != null &&  !map.get("type").toString().equals("") ){
                    if(map.get("type").toString().equals("STUDENT")){
                        row.put("type","学生");
                    }else if(map.get("type").toString().equals("GETI")){
                        row.put("type","个体");
                    }
                }else {
                    row.put("type","");
                }

               if(map.get("realName") != null &&  !map.get("realName").toString().equals("") ){
                    row.put("realName",map.get("realName").toString());
                }else {
                    row.put("realName","");
                }

                if( map.get("classes") != null  && !map.get("classes").toString().equals("")){
                    row.put("classes",map.get("classes").toString());
                }else {
                    row.put("classes","");
                }

                if(map.get("servicePhone") != null  && !map.get("servicePhone").toString().equals("")  ){
                    row.put("servicePhone",map.get("servicePhone").toString());
                }else {
                    row.put("servicePhone","");
                }
                if( map.get("weChat") != null &&!map.get("weChat").toString().equals("") ){
                    row.put("weChat",map.get("weChat").toString());
                }else {
                    row.put("weChat","");
                }
                if( map.get("pcount") != null && !map.get("pcount").toString().equals("")   ){
                    row.put("pcount",map.get("pcount").toString());
                }else {
                    row.put("pcount","");
                }

                dataList.add(row);
        }

        File file = CSVUtils.createCSVFile(dataList , headerMap , "商户列表");
        renderBinary(file);

    }

}
